package com.sunyard.authorization.config;

import com.sunyard.authorization.service.ManageOperatorService;
import com.sunyard.dal.bo.operator.OperatorLoginBO;
import com.sunyard.dal.dto.OperatorDTO;
import com.sunyard.dal.mapper.OperatorMapper;
import com.sunyard.dal.mapper.PopedomMapper;
import com.sunyard.redisUtil.RedisUtils;
import com.sunyard.utils.TokenUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class ManageRealm extends AuthorizingRealm {

    @Autowired
    private OperatorMapper operatorMapper;

    @Autowired
    private PopedomMapper popedomMapper;

    @Autowired
    private ManageOperatorService manageOperatorService;

    @Autowired
    private RedisUtils redisUtils;

    Logger log = LoggerFactory.getLogger(ManageRealm.class);

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("Manage权限验证");
        String username = TokenUtil.getOpName(principalCollection.toString());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(getPopedomList(username));
        return info;
    }

    private List<String> getPopedomList(String username) {
        OperatorDTO operator = operatorMapper.getOperatorDTOByOpName(username);
        String key = "popedomList:" + operator.getRoleId();
        List<String> popedomList = null;
        popedomList = redisUtils.get(key, List.class);
        if (popedomList == null) {
            popedomList = popedomMapper.getShiroList(operator.getRoleId());
            redisUtils.set(key, popedomList);
        }
        return popedomList;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("Manage身份认证");
        CustomizedToken authentication = (CustomizedToken) authenticationToken;
        try {
            login(authentication);
        } catch (IllegalAccessException e) {
            throw new AuthenticationException(e.getMessage());
        }
        return new SimpleAuthenticationInfo(authentication.getPrincipal()
                , authentication.getPassword(), "ManageRealm");
    }

    private boolean login(CustomizedToken authentication) throws IllegalAccessException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        try {
            manageOperatorService.login(response, request, convertToLoginBo(authentication));
        } catch (Exception e) {
            throw new IllegalAccessException(e.getMessage());
        }
        return true;
    }

    private OperatorLoginBO convertToLoginBo(CustomizedToken customizedToken) {
        OperatorLoginBO operatorLoginBO = new OperatorLoginBO();
        operatorLoginBO.setOpName(customizedToken.getUsername());
        operatorLoginBO.setOpPwd(String.valueOf(customizedToken.getPassword()));
        return operatorLoginBO;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof CustomizedToken;
    }

}
